package com.situ.day15;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class ReflectDemo {
	@Test
	public void classTest() throws ClassNotFoundException {
		//1.Class.forName(类路径)
		Class clazz1 = Class.forName("com.situ.day15.Person");
		//2. 类名.class
		Class clazz2 = Person.class;
		//3. 对象.getClass();
		Person person = new Person();
		Class clazz3 = person.getClass();
		
		System.out.println(clazz1 == clazz2);//true
		System.out.println(clazz1 == clazz3);//true
	}
	
	@Test
	public void constructorTest() {
		Class clazz = Person.class;
		//得到 所有构造方法，包括private的构造方法
		Constructor[] constructors = clazz.getDeclaredConstructors();
		for (Constructor constructor : constructors) {
			System.out.println(constructor);
			System.out.println(constructor.getName());//构造方法的名字
			System.out.println(constructor.getModifiers());//返回值
		}
	}
	
	@Test
	public void constructorTest1() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazz = Person.class;
		//得到指定参数的构造方法对象
		Constructor constructor = clazz.getConstructor(String.class, Integer.class);
		System.out.println(constructor);
		//constructor.newInstance("zhangsan", 20);
		//调用newInstance实例化对象，需要强制类型转换成Person
		Person person = (Person) constructor.newInstance(new Object[]{"zhangsan", 20});
		System.out.println(person);
	}

	@Test
	public void methodTest() throws Exception {
		//Person person = new Person();
		//person.setName("张三");
		
		Class clazz = Class.forName("com.situ.day15.Person");
		//得到无参数构造方法
		Constructor constructor = clazz.getConstructor();
		//调用newInstance实例化对象
		Person person = (Person) constructor.newInstance();
		//person.setName("张三");
		//clazz.getMethod("setName", new Class[]{String.class});
		Method method = clazz.getMethod("setName", String.class);
		//method.invoke(person, new Object[]{"张三"});
		method.invoke(person, "张三");
		System.out.println(person);
	}
	
}
